package cn.zmit.kuxi.activity;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.request.RequestTask;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.SystemUtils;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.cache.CacheData;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.interfaces.OnRequestListener;
import com.xdroid.utils.AppManager;

/** * @author chenxu @parameter * @return */
public class SplashActivity extends BaseActivity {
	protected static final int PROGRESS_UPDATE = 0;
	@ViewInject(R.id.rl_splash)
	private RelativeLayout rl_splash;
	@ViewInject(R.id.tv_version)
	private TextView tv_version;

	// ProgressDialog dialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_splash);
		ViewUtils.inject(this);
		initView();
	}

	protected void initView() {
		tv_update = (TextView) findViewById(R.id.tv_update);
		pb_update = (ProgressBar) findViewById(R.id.pb_update);
		pb_update.setMax(100);
		AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 1.0f);
		alphaAnimation.setDuration(2000);
		rl_splash.startAnimation(alphaAnimation);
		alphaAnimation.setAnimationListener(new AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onAnimationEnd(Animation animation) {

				checkUpdate(SplashActivity.this, true);
				// enterHome();
			}
		});
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	private TextView tv_update;
	private ProgressBar pb_update;

	// 版本更新//////////////////////////////////////////////////////////////

	private int newest_version_code;
	private int to_update;
	private String apkurl;

	protected void checkUpdate(final BaseActivity activity,
			final Boolean isShowTip) {
		// Map<String, Object> map = new HashMap<String, Object>();
		// map.put("vesion_code", currentVersionCode);
		Log.e("checkin==", "in...");
		final int currentVersionCode = SystemUtils.getAppVersionCode(this);
		RequestTask.getInstance().doUpdateApp(activity, currentVersionCode,
				new OnRequestListener() {

					@Override
					public void onRequestPrepare() {

					}

					@Override
					public void onRequestFinish(String data) {

					}

					@Override
					public void onRequestFailed(String error) {
						enterHome();
						Toast.makeText(SplashActivity.this, "网络异常！", 0).show();
					}

					@Override
					public void onCacheDataLoadFinish(CacheData cacheData) {

					}

					@Override
					public void onDone(XDroidRequest request, String response,
							DataType dataType) {

						if (response != null) {
							Log.e("reponsein==", "in...");
							JSONObject obj;
							try {
								obj = new JSONObject(response);
								to_update = obj.getInt("to_update");
								apkurl = obj.getString("dl_url");
								newest_version_code = obj
										.getInt("newest_version_code");
							} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

							if (newest_version_code > currentVersionCode) {
								final AlertDialog.Builder builder = new AlertDialog.Builder(
										activity);
								builder.setTitle("更新");
								builder.setMessage("检测到有更新,是否立刻更新？");
								builder.setOnCancelListener(new OnCancelListener() {

									@Override
									public void onCancel(DialogInterface dialog) {
										AppManager.getInstance()
												.killAllActivity();
									}
								});
								builder.setNegativeButton("稍后更新",
										new OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												if (to_update == 0) {
													enterHome();
												} else if (to_update == 1) {
													Toast.makeText(
															SplashActivity.this,
															"此版本必须更新!", 0)
															.show();
													// AppManager.getInstance()
													// .killAllActivity();
													builder.create().show();
												}

											}
										});
								builder.setPositiveButton("立刻更新",
										new OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												download();
											}

										});
								builder.create().show();
							} else {
								if (isShowTip) {
									enterHome();
								}
							}
						}
					}

				});
	}

	private int progress;

	private void download() {
		// 判断sd卡是否可用
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			String target = Environment.getExternalStorageDirectory()
					+ "/kuxi.apk";
			// XUtils
			HttpUtils utils = new HttpUtils();
			utils.download(apkurl, target, new RequestCallBack<File>() {// 回调方法

						// 下载文件的进度
						@Override
						public void onLoading(long total, long current,
								boolean isUploading) {
							super.onLoading(total, current, isUploading);
							tv_update.setVisibility(View.VISIBLE);// 显示进度可见
							tv_update.setText(current * 100 / total + "%");

							progress = (int) ((current / (double) total) * 100);
							pb_update.setVisibility(View.VISIBLE);
							pb_update.setProgress(progress);

						}

						// 下载成功
						@Override
						public void onSuccess(ResponseInfo<File> arg0) {
							Toast.makeText(context, "下载成功", 0).show();
							// 跳转到系统下载页面
							// Intent intent = new Intent(Intent.ACTION_VIEW);
							// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							// intent.setDataAndType(Uri.fromFile(arg0.result),
							// "application/vnd.android.package-archive");
							// startActivityForResult(intent, 0);
							// android.os.Process.killProcess(android.os.Process
							// .myPid());
							// finish();
							Intent i = new Intent(Intent.ACTION_VIEW);
							i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
							i.setDataAndType(Uri.fromFile(arg0.result),
									"application/vnd.android.package-archive");
							startActivity(i);
							android.os.Process.killProcess(android.os.Process
									.myPid());
						}

						// 下载失败
						@Override
						public void onFailure(HttpException arg0, String arg1) {
							Toast.makeText(SplashActivity.this, "下载失败!",
									Toast.LENGTH_SHORT).show();
						}
					});
		} else {
			Toast.makeText(SplashActivity.this, "sdcard不可用!",
					Toast.LENGTH_SHORT).show();
		}

	}

	/**
	 * 用户取消安装回调此方法
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		enterHome();
	}

	/**
	 * 进入主界面
	 */
	protected void enterHome() {
		Boolean isFirst = PreferenceHelper.readBoolean(SplashActivity.this,
				SPConstants.SHARED_PREFERENCE_NAME,
				SPConstants.IS_FIRST_LAUNCH, true);
		if (isFirst) {
			openActivity(GuideActivity.class);
			finish();
			PreferenceHelper.write(SplashActivity.this,
					SPConstants.SHARED_PREFERENCE_NAME,
					SPConstants.IS_FIRST_LAUNCH, false);
		} else {
			Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
			startActivity(intent);
			finish();
		}

	}
}
